<template>
  <div class="app-container app-container-next app-container-detail">
    <el-card class="box-card site" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'goods-list'}">
          <el-button plain icon="el-icon-back" size="small" :round="true">
            返回
          </el-button>
        </router-link>
      </div>
      <el-form :model="goods" :rules="rules" label-position="top" ref="ruleForm" label-width="100px" class="side-form">
        <div class="basic-section">
          <div class="container left-side">
            <h4>基本信息</h4>
            <el-form-item label="商品标题：" prop="spuName">
              <el-input v-model.trim="goods.spuName" minlength="1"  maxlength="255" show-word-limit></el-input>
            </el-form-item>
            <!--            <div class="item-label" style="display: flex; align-items: center">-->
            <!--              <span style="width: 80px">商品标题：</span>-->
            <!--              <el-input v-model="goods.spuName" minlength="1"  maxlength="255" show-word-limit></el-input>-->
            <!--            </div>-->
            <p class="title" style="font-size: 14px;margin: 0;margin-bottom: 10px">商品描述：</p>
            <tinymce  v-model="goods.spuDescription" :height="500"/>
          </div>
          <div class="container right-side">
            <h4>基本属性</h4>
<!--            <div class="item-label">
              <span>SPU：</span>
              {{ goods.spuCode }}
            </div>
            <div class="item-label">
              <span>商品类型：</span>
              {{ goods.spuType === '1' ? '定制商品' : '普通商品'}}
            </div>
            <div class="item-label">
              <span>虚拟销量：</span>
              {{ goods.virtualSalesQty }}
            </div>-->
            <div class="item-label">
              <span>是否上架：</span>
              <el-switch v-model="isPublished">
              </el-switch>
            </div>
<!--            <el-form-item :label="`商品系列：(${spuSeriesList.length})`" prop="series" style="margin-bottom: 10px;" class="full-width">
              <template #label>
                <div  style="display: flex;justify-content: space-between">
                  <span>商品系列：({{spuSeriesList.length}})</span>
                  <span @click="showMore=!showMore">{{showMore ? '收起' : '展开'}}</span>
                </div>
              </template>
              <div class="good-tags">
                <el-tag
                    v-show="!showMore ? index < 3 : item "
                    class="good-tags-item"
                    :key="item.value"
                    v-for="(item, index) in spuSeriesList"
                    effect="plain"
                    @click="toSeriesDetail(item.value)">
                  {{ item.label }}
                </el-tag>
              </div>
            </el-form-item>-->
            <el-form-item label="商品标签：" prop="tags">
              <el-select v-model="checkedTagList"
                         multiple
                         filterable
                         allow-create
                         default-first-option
                         placeholder="输入或下拉选择，最多输入60个">
                <el-option
                    v-for="item in tagList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
<!--            <h4>SEO</h4>
            <div class="seo-btns">
              <el-button type="text" icon="el-icon-edit" @click="showSEOEditor">编辑SEO</el-button>
              <el-button type="text" icon="el-icon-view" @click="checkSEOInfo">查看收录</el-button>
              <el-button type="text" icon="el-icon-upload2" @click="submitSEOInfo">手动提交</el-button>
            </div>-->
          </div>
        </div>
        <h4 style="margin-top: 30px;">产品图片</h4>
        <el-form-item class="list-wrap" style="min-height: 100px" prop="imagesList">
          <draggable v-model="goods.imagesList" chosenClass="active" animation="100" filter=".forbid" :preventOnFilter="false">
          <div
              class="image-item"
              v-for="($item, $index) in goods.imagesList"
              :key="$index"
          >
            <div class="img">
              <el-image  v-img-host="{url: fillImg($item.src)}" :src="bgPic"  alt="" class="l-img" />
              <div class="img_mask" v-if="$item.flag">
                <svg-icon class="icon" icon-class="checked"/>
              </div>
              <div class="label">
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <div @click.stop.prevent="actionDel($index)">
                    <svg-icon icon-class="remove"></svg-icon>
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>
          </draggable>
          <ele-form-upload-plus-file   v-model="imagesList" :multiple="true" imageHeight="133px"/>
        </el-form-item>
        <h4 style="margin-top: 30px;">
          <el-checkbox v-model="goods.singleton" :true-label="0" :false-label="1" @change="handleSettingSku">有多个款式、规格</el-checkbox>
           <el-button type="primary" size="mini" @click="settingVisible = true" v-if="goods.singleton === 0">添加规格</el-button>
        </h4>
        <div style="text-align: center" v-if="!goods.skuList.length && goods.singleton === 0">
          <p style="font-size: 18px; margin-bottom: 20px;">添加你的商品款式</p>
        </div>
        <el-table :data="batchSettings" fit highlight-current-row v-if="goods.skuList.length && goods.singleton === 0">
          <el-table-column align="center" label="商品链接" width="200px">
            <template>
              商品链接
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品图片">
            <template>
              商品图片
            </template>
          </el-table-column>
          <el-table-column align="center" :label="optionsKeys[0]"  :show-overflow-tooltip="true" v-if="optionsKeys.length">
            <template>
              --
            </template>
          </el-table-column>
          <el-table-column align="center" :label="optionsKeys[1]"  :show-overflow-tooltip="true" v-if="optionsKeys.length&&optionsKeys.length>1" >
            <template>
              --
            </template>
          </el-table-column>
          <el-table-column align="center" :label="optionsKeys[2]"  :show-overflow-tooltip="true" v-if="optionsKeys.length&&optionsKeys.length > 2" >
            <template>
              --
            </template>
          </el-table-column>
          <el-table-column align="center" :label="'销售价(' + currencyType + ')'" width="200px">
            <template slot-scope="scope">
              <el-form-item>
                <el-input-number
                    v-model="scope.row.sellPrice"
                    :clearable="true"
                    :controls="false"
                    :precision="2"
                    :min="0"
                    style="width: 100%;"
                    @input="handleAllDiscount(scope.row.sellPrice, 'sellPrice')"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="'虚拟价(' + currencyType + ')'" width="200px">
            <template slot-scope="scope">
              <el-form-item>
                <el-input-number
                    v-model="scope.row.virtualSellPrice"
                    :clearable="true"
                    :controls="false"
                    :precision="2"
                    :min="0"
                    style="width: 100%;"
                    @input="handleAllDiscount(scope.row.virtualSellPrice, 'virtualSellPrice')"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="重量(g)" width="200px">
            <template slot-scope="scope">
              <el-form-item>
                <el-input style="width: 180px" v-model="scope.row.weight"
                          @input="handleAllDiscount(scope.row.weight, 'weight')"
                          onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))">
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template>
              --
            </template>
          </el-table-column>
        </el-table>
        <el-table :data="goods.skuList" fit highlight-current-row :class="{'hidden-table-header': goods.skuList.length > 0 && goods.singleton === 0}" v-if="goods.skuList.length">
          <el-table-column align="center" label="图片链接" width="200px">
            <template slot-scope="scope">
              <el-form-item :prop="'skuList.' + scope.$index + '.skuImage'" :rules="[{required: true, message: '请选择图片', trigger: 'blur'}]">
                <el-select v-model="scope.row.skuImage" placeholder="请选择" @change="handleSelectImg(scope.$index, scope.row.skuImage)">
                  <el-option v-for="(item, index) in goods.imagesList" :value="item.src" :label="item.src" :key="index">
<!--                    <span style="float: left">{{ item.src }}</span>-->
                    <el-image
                        style="width: 48px; height: 36px;cursor: pointer;"
                        :src="item.src"
                        fit="contain"></el-image>
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品图片" >
            <template slot-scope="scope">
                <el-image
                    v-if="scope.row.skuImage"
                    slot="reference"
                    style="width: 80px; height: 60px;cursor: pointer;"
                    :src="scope.row.skuImage"
                    fit="contain"></el-image>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="optionsKeys[0]" prop="color" :show-overflow-tooltip="true" v-if="optionsKeys.length"/>
          <el-table-column align="center" :label="optionsKeys[1]" prop="size" :show-overflow-tooltip="true" v-if="optionsKeys.length&&optionsKeys.length>1" />
          <el-table-column align="center" :label="optionsKeys[2]" prop="other" :show-overflow-tooltip="true" v-if="optionsKeys.length&&optionsKeys.length>2" />
          <el-table-column align="center" :label="'销售价(' + currencyType + ')'" prop="sellPrice" :width="goods.singleton === 0 ? '200px' : 'auto'">
            <template slot-scope="scope">
              <el-form-item :prop="'skuList.' + scope.$index + '.sellPrice'" :rules="[{required: true, message: '价格不能为空', trigger: 'blur'}]">
<!--                <el-input v-model.number="scope.row.sellPrice" />-->
                <el-input-number
                    v-model="scope.row.sellPrice"
                    :clearable="true"
                    :controls="false"
                    :precision="2"
                    :min="0"
                    placeholder="请输入价格"
                    style="width: 100%;"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="'虚拟价(' + currencyType + ')'" :width="goods.singleton === 0 ? '200px' : 'auto'">
            <template slot-scope="scope">
              <el-form-item>
                <el-input-number v-model.number="scope.row.virtualSellPrice" :clearable="true"
                                 :controls="false"
                                 :precision="2"
                                 :min="0"
                                 placeholder="请输入虚拟价"
                                 style="width: 100%;" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="重量(g)" :width="goods.singleton === 0 ? '200px' : 'auto'">
            <template slot-scope="scope">
              <el-form-item :prop="'skuList.' + scope.$index + '.weight'" :rules="[{validator: checkNumber, trigger: 'blur'}]">
                <el-input v-model.number="scope.row.weight"  placeholder="请输入重量" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" v-if="goods.singleton === 0">
            <template slot-scope="scope">
              <el-button size="mini" plain type="danger" @click="handleRemove(scope.$index)" style="margin-bottom: 22px;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item class="fixBottom">
          <el-button type="primary" @click="handleSettings('ruleForm')">保存</el-button>
          <!--<el-button @click="handleAllCancel()">取消</el-button>-->
        </el-form-item>
      </el-form>
    </el-card>
    <el-drawer
        size="400px"
        title="编辑SEO"
        :wrapperClosable="false"
        :visible.sync="dialogVisible"
        class="good-setting-panel">
      <el-form :model="spuSeo" :rules="seoRules" ref="spuSeoForm" label-width="100px" class="demo-ruleForm"
               label-position="top">
        <el-form-item label="SEO标题" prop="spuName" placeholder="请输入">
          <template #label>
            <div class="sit-customer-label">
              SEO标题
              <p>标题是SEO最重要的部分，该标题会显示在搜索引擎的搜索结果中。</p>
            </div>
          </template>
          <el-input v-model="spuSeo.title" maxlength="2000" show-word-limit placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="SEO描述" prop="description">
          <template #label>
            <div class="sit-customer-label">
              SEO描述
              <p>这是该商品的整体SEO描述，可以添加一些商品描述，使商品在搜索引擎中获得更高的排名。</p>
            </div>
          </template>
          <el-input v-model="spuSeo.description" type="textarea" maxlength="5000" show-word-limit
                    placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="SEO关键词" prop="checkedKeywordsList">
          <el-select
              style="width: 100%"
              v-model="checkedKeywordsList"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="回车确认，可添加多个">
            <el-option v-for="item in seoKeywordsList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSeoReset('spuSeoForm')">取消</el-button>
          <el-button type="primary" @click="handleEditSeo('spuSeoForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-dialog :visible.sync="settingVisible" title="规格（最多添加3个属性）" width="600px">
      <el-form ref="skuOptionForm" :model="skuOption" style="padding-left: 0;padding-right: 0">
        <draggable v-model="skuOption.data" chosenClass="active" animation="500" filter=".forbid"
                   :preventOnFilter="false">
        <template v-for="(item, index) in skuOption.data">
          <div class="sku-option" :key="index">
            <el-form-item label="" :prop="'data.' + index + '.name'" :rules="[{required: true, message: '请输入款式名称', trigger: 'blur'}, {required: true, pattern: /^[^\,]*$/, message: '名称不能带有,'}]">
              <span class="jyfont  card-col-move"></span>
              <el-input v-model="item.name" placeholder="请输入款式名称" class="forbid"></el-input>
              <i style="margin-left: 12px" class="icon el-icon-delete"
                 @click="handleRemoveLevel(index)" v-if="skuOption.data.length>1"></i>
            </el-form-item>
            <el-form-item :prop="'data.' + index + '.items'" :rules="[{required: true, message: '请输入属性值', trigger: 'blur'}]" >
              <drag-tag v-model="item.items"></drag-tag>
<!--               <div class="options-tags forbid">
                 <draggable v-model="item.items"  animation="500" chosenClass="active"  filter=".forbid1"
                            :preventOnFilter="false">
                 <div class="options-tag" v-for="(value, indexs) in item.items" :key="indexs">
                   <i class="jyfont  card-col-move"></i>
                   <div class="options-tag-inp">
                     <div class="one-line">{{value}}</div>
                   </div>
                   <i class="el-tag__close el-icon-close" @click="handleRemoveTag(index, indexs)"></i>
                 </div>
                   <el-input
                       style="flex-grow: 1; width: 0.0961538%; max-width: 100%; min-width: 100px;"
                       class="options-input forbid1"
                       placeholder="输入属性值，多个属性enter输入"
                       v-model="tagInputValue"
                       ref="saveTagInput"
                       size="small"
                       @keyup.enter.native="handleInputConfirm(index)"
                   >
                   </el-input>
                 </draggable>

               </div>-->
<!--              <el-select v-model="item.items"
                         class="no-down sku-item forbid"
                         style="width: 100%"
                         :popper-append-to-body="false"
                         multiple
                         filterable
                         allow-create
                         default-first-option
                         placeholder="请输入属性值，多个属性enter输入">
                <el-option
                    v-for="items in colors"
                    :key="items.value"
                    :label="items.label"
                    :value="items.value">
                </el-option>
              </el-select>-->
            </el-form-item>
          </div>

        </template>
        </draggable>
        <el-button type="primary" @click="addOption" v-if="skuOption.data.length<3" size="mini">添加属性</el-button>
        <el-form-item style="margin-top: 20px">
          <el-button type="primary" @click="batchModifySetting('skuOptionForm')" :loading="submitLoading">
            保存
          </el-button>
          <el-button @click="settingVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import bgPic from '@/assets/images/bg-grey.png';
import {currency} from '@/utils/filters';
import draggable from 'vuedraggable';
import dragTag from '@/views/goods/components/dragTag';
import Tinymce from '@/components/Tinymce';
import {mapGetters} from 'vuex';
import { addSpu } from '@/api/goods';
import {getListForDecoration} from '@/api/domain';
import axios from 'axios';
export default {
    name: 'goods-add',
    components: { draggable, Tinymce, dragTag },
    data () {
        const checkNumber = (rule, value, callback) => {
            let num = /^(0|[1-9]\d*)/;
            console.log(value);
            if (value && !(num.test(value))) {
                callback(new Error('请输入大于0的整数'));
            } else {
                callback();
            }
        };
        return {
            checkNumber,
            showMore: false,
            topImage: [],
            bgPic,
            visible: false,
            spuId: this.$route.params.id,
            fixOption: {fixedHeader: true},
            isPublished: false,
            imageUrl: [],
            batchSettings: [{}],
            goods: {
                siteId: this.siteId,
                spuName: '',
                spuCode: '',
                spuDescription: '',
                virtualSalesQty: 0,
                published: 0,
                spuTags: '',
                spuSeries: '',
                seoTitle: '',
                seoDescription: '',
                seoLink: '',
                seoKeywords: '',
                optionsList: [],
                imagesList: [],
                skuList: [],
                singleton: 1
            },
            imagesList: [],
            skuOption: {
                data: [
                    {
                        'items': [],
                        'name': ''
                    }
                ]
            },
            optionsKeys: [],
            pageParams: {
                page: 1,
                pageSize: 20
            },
            specList: [],
            rules: {
                spuName: [
                    {required: true, message: '请输入商品标题', trigger: 'blur'}
                ],
                imagesList: [
                    {required: true, message: '请选择图片', trigger: 'blur'}
                ]
            },
            value: [],
            options: [],
            dialogVisible: false,
            settingVisible: false,
            seo: {},
            seoRules: {
                title: [{required: true, message: '请填写SEO标题', trigger: 'blur'}],
                description: [{required: true, message: '请填写SEO描述', trigger: 'blur'}]
            },
            spuSeo: {title: '', description: '', keywords: ''},
            setSpuSeo: false, // 更新SEO
            seoKeywordsList: [],
            checkedKeywordsList: [],
            skuOptionRules: {
                items: [
                    {required: true, message: '请输入属性', trigger: 'blur'}
                ]
            },
            virtualSalesPrice: {unit: '$'},
            submitLoading: false,
            spuSeriesList: [],
            tagList: [], // SPU所有标签
            checkedTagList: [], // 已分配的标签
            setVirtualPrice: false, // 设置虚拟价
            colors: [],
            sizes: []
        };
    },
    computed: {
        ...mapGetters(['siteList']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencyType () {
            return this.siteInfo.currencyType;
        }
    },
    watch: {
        'imagesList': {
            deep: true,
            handler (value) {
                let obj = {};
                this.goods.imagesList = [...this.goods.imagesList, ...value].reduce((cur, next) => {
                    // eslint-disable-next-line no-unused-expressions
                    obj[next.src] ? '' : obj[next.src] = true && cur.push(next);
                    return cur;
                }, []);
            }
        }
    },
    mounted () {
        this.handleSettingSku();
    },
    methods: {
        actionDel (index) {
            this.goods.imagesList.splice(index, 1);
        },
        parseJson (value) {
            return JSON.parse(value);
        },
        customizeType (data) {
            let input;
            // skuEffortBackImage 背镂空图, skuEffortBackImageFont 背主图, skuEffortFrontImage 前镂空图, skuEffortFrontImageFont 前主图
            // 0：没有预览图片  1.有预览图片
            const {bindingImage} = JSON.parse(data);

            switch (this.type) {
            case '1':
                input = bindingImage === '1' ? '图片(有预览图)' : '图片';
                break;
            case '2':
                input = bindingImage === '1' ? '文字(有预览图)' : '文字';
                break;
            case '3':
                input = '图文';
                break;
            }
            return input;
        },
        handlePreview () {
            let url = 'https://' + this.siteInfo.domainName + `/products/${this.goods.fullName.replace(/%/g, '%25')}`;
            window.open(url, '_blank');
        },
        toSeriesDetail (seriesId) {
            this.$router.push({name: 'series-detail', params: {id: seriesId}});
        },
        descartes (list) {
            // parent 上一级索引;count 指针计数
            let point = {}; // 准备移动指针
            let result = []; // 准备返回数据
            let pIndex = null; // 准备父级指针
            let tempCount = 0; // 每层指针坐标
            let temp = []; // 组装当个 sku 结果

            // 一：根据参数列生成指针对象
            for (let index in list) {
                if (typeof list[index] === 'object') {
                    point[index] = { parent: pIndex, count: 0 };
                    pIndex = index;
                }
            }

            // 单维度数据结构直接返回
            if (pIndex === null) {
                return list;
            }

            // 动态生成笛卡尔积
            while (true) {
                // 二：生成结果
                let index;
                for (index in list) {
                    tempCount = point[index].count;
                    temp.push(list[index][tempCount]);
                }
                // 压入结果数组
                result.push(temp);
                temp = [];

                // 三：检查指针最大值问题，移动指针
                while (true) {
                    if (point[index].count + 1 >= list[index].length) {
                        point[index].count = 0;
                        pIndex = point[index].parent;
                        if (pIndex === null) {
                            return result;
                        }
                        // 赋值 parent 进行再次检查
                        index = pIndex;
                    } else {
                        point[index].count++;
                        break;
                    }
                }
            }
        },
        batchModifySetting (name) {
            if (!this.skuOption.data.length) {
                return this.$message.error('至少添加一个属性');
            }
            this.$refs[name].validate(valid => {
                if (valid) {
                    let skuOption = [];
                    this.optionsKeys = this.skuOption.data.map(s => s.name);
                    const items = this.skuOption.data.map(s => s.items);
                    const maps = this.descartes(items);
                    const obj = {
                        color: '',
                        size: '',
                        sellPrice: undefined,
                        virtualSellPrice: undefined,
                        skuPrice: '',
                        skuImage: '',
                        weight: ''
                    };
                    maps.forEach((res, index) => {
                        const o = this.optionsKeys.length === 1 ? this.goods.skuList.find(s => res.includes(s.color)) : this.optionsKeys.length === 2 ? this.goods.skuList.find(s => res.includes(s.color) && res.includes(s.size)) : this.goods.skuList.find(s => res.includes(s.color) && res.includes(s.size) && res.includes(s.other));
                        const key = this.optionsKeys.length === 1 ? `${this.optionsKeys[0]}:${res[0]}` : this.optionsKeys.length === 2 ? `${this.optionsKeys[0]}:${res[0]},${this.optionsKeys[1]}:${res[1]}` : `${this.optionsKeys[0]}:${res[0]},${this.optionsKeys[1]}:${res[1]},${this.optionsKeys[2]}:${res[2]}`;
                        skuOption.push({
                            ...obj, ...o, color: res[0], size: res[1], other: res[2], skuValues: key, sort: index + 1
                        });
                    });
                    this.goods.skuList = skuOption;
                    this.settingVisible = false;
                    this.batchSettings.forEach(s => {
                        s.sellPrice && this.handleAllDiscount(s.sellPrice, 'sellPrice');
                        s.virtualSellPrice && this.handleAllDiscount(s.virtualSellPrice, 'virtualSellPrice');
                        s.weight && this.handleAllDiscount(s.weight, 'weight');
                    });
                }
            });
        },
        handleReset (name) {
            this.$refs[name].resetFields();
            this.settingVisible = false;
            this.setVirtualPrice = false;
        },
        changeVirtualPriceFormula (data) {
            if (data === 'ADD_PERCENT_VALUE') {
                this.virtualSalesPrice.unit = '%';
            } else {
                this.virtualSalesPrice.unit = '$';
            }
        },
        handleSettings (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    const options = [];
                    this.skuOption.data.forEach(res => {
                        options.push({name: res.name, items: res.items.join(',')});
                    });
                    let params = {
                        images: this.goods.imagesList.map(res => res.src),
                        spuName: this.goods.spuName,
                        siteId: this.siteId,
                        skuList: this.goods.skuList,
                        options,
                        singleton: this.goods.singleton,
                        spuTags: this.checkedTagList.join(','),
                        published: this.isPublished ? 1 : 0,
                        spuDescription: this.goods.spuDescription
                    };
                    console.log(params);
                    this.submitLoading = true;
                    addSpu(params).then(res => {
                        if (res.code === '200') {
                            getListForDecoration(this.siteId).then(res => {
                                res.data.map(s => {
                                    const url = s.domainName + `/products/${this.goods.fullName.replace(/%/g, '%25')}`;
                                    axios.get(`https://${s.domainName}/refreshAloneCache?path=${url}`);
                                });
                            });
                            this.$message.success('保存成功');
                            this.$router.push({name: 'goods-list'});
                        } else {
                            this.$message.error(res.message);
                        }
                        this.submitLoading = false;
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        showSEOEditor () {
            this.seoKeywordsList = [];
            this.checkedKeywordsList = [];
            this.dialogVisible = true;
            this.spuSeo.title = this.goods.seoTitle;
            this.spuSeo.description = this.goods.seoDescription;
            this.spuSeo.keywords = this.goods.seoKeywords;
            let keywords = this.goods.seoKeywords;
            if (keywords == null || keywords === '') {
                return false;
            }
            let keywordsList = keywords.split(',');
            this.checkedKeywordsList = keywordsList;
            let tempList = [];
            keywordsList.forEach(item => {
                tempList.push({'label': item, 'value': item});
            });
            this.seoKeywordsList = tempList;
        },
        handleEditSeo (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.dialogVisible = false;
                    this.setSpuSeo = true;
                    this.spuSeo.keywords = this.checkedKeywordsList.join(',');
                } else {
                    this.$message.error('请先设置有效的SEO信息！');
                }
            });
        },
        handleSeoReset (name) {
            this.$refs[name].resetFields();
            this.dialogVisible = false;
            this.setSpuSeo = false;
        },
        computeVirtualSellValue (method, value, origin) {
            if (method == null || method === '' || value == null || value === '') {
                return origin;
            }
            if (method === 'FIX_VALUE') {
                return Math.floor(parseFloat(value) * 100);
            }
            if (method === 'ADD_FIX_VALUE') {
                return Math.floor(parseFloat(value) * 100 + origin);
            }
            if (method === 'ADD_PERCENT_VALUE') {
                return Math.floor(origin * (1 + parseFloat(value) / 100.0));
            }
            return origin;
        },
        handleAllCancel () {
            this.setSpuSeo = false;
            this.setVirtualPrice = false;
            this.$refs['el-search-table'].fetchHandler(self.pageParams, false);
        },
        delSkuDetail (id) {
            let skuId = id;
            let siteId = this.siteId;
            this.$confirm('您确认要删除此款式吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

            }, () => {
            });
        },
        checkSEOInfo () {
            let seoLink = this.goods.seoLink;
            if (seoLink) {
                let checkURL = 'https://www.google.com/search?q=info:' + seoLink;
                window.open(checkURL, '_blank');
            }
        },
        submitSEOInfo () {
            let seoLink = this.goods.seoLink;
            if (seoLink) {
                let submitURL = 'https://www.google.com/webmasters/tools/submit-url?urlnt=' + seoLink;
                window.open(submitURL, '_blank');
            }
        },
        // 错误图片显示
        fillImg (src) {
            const match = /(http|https):\/\/([\w.]+\/?)\S*/;
            return !match.test(src) ? `https://tlkj-item-pic.oss-cn-beijing.aliyuncs.com${src}` : src;
        },
        handleRemove (index) {
            this.goods.skuList.splice(index, 1);
        },
        // 批量计算
        handleAllDiscount (val, key) {
            this.goods.skuList.forEach((res) => {
                res[key] = val;
            });
        },
        // 添加属性
        addOption () {
            if (this.skuOption.data.length < 4) {
                this.skuOption.data.push({name: '', items: []});
            }
        },
        handleRemoveLevel (index) {
            this.skuOption.data.splice(index, 1);
        },
        handleSettingSku () {
            this.optionsKeys = [];
            this.goods.skuList = [];
            this.skuOption = {
                data: [
                    {
                        'items': [],
                        'name': ''
                    }
                ]
            };
            if (this.goods.singleton === 1) {
                this.skuOption = {
                    data: [
                        {
                            'items': ['DEFAULT'],
                            'name': 'COLOR'
                        }
                    ]
                };
                this.goods.skuList.push(
                    {
                        sort: 1,
                        skuValues: 'COLOR:DEFAULT',
                        sellPrice: undefined,
                        virtualSellPrice: undefined,
                        skuPrice: '',
                        skuImage: '',
                        weight: ''
                    }
                );
            }
        },
        handleSelectImg (index, img) {
        // 找出所有同一种颜色的sku
            const sameColor = this.goods.skuList.filter(s => s.color === this.goods.skuList[index].color);
            sameColor.forEach(res => {
                res.skuImage = img;
            });
        }
    }
};
</script>

<style scoped lang="scss">
.sit-customer-label {
  p {
    font-size: 14px;
    color: #7e849c;
    line-height: 22px;
    margin-bottom: 7px;
    margin-top: 0;
  }
}

.preview-pop {
  display: flex;
  align-items: center;

  .img {
    margin-right: 10px;
    width: 120px;
  }
}

#icon {
  position: absolute;
  z-index: 1;
  margin: 17px 70px;
  color: rgb(163, 162, 162);
  cursor: pointer;
  font-size: 24px;
}
.list-wrap {
  width: 100%;
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
  margin-top: 20px;

  .image-item {
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
    border-radius: 0;
    overflow: hidden;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: center;
    .img_mask {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      border: 2px solid #1F7DF8;
      background-color: rgba(0, 0, 0, 0.3);

      .icon {
        position: absolute;
        width: 40px;
        height: 40px;
        top: 50%;
        left: 50%;
        margin-left: -20px;
        margin-top: -20px;
      }
    }

    .img {
      position: relative;
      .label{
        display: none;
      }

      .l-img {
        width: 100px;
        height: 133px;
        object-fit: cover;
      }

      &:hover {
        .label {
          display: flex;
          align-items: center;
          justify-content: center;
          position: absolute;
          left: 0;
          top: 0;
          right: 0;
          bottom: 0;
          border: 1px solid #1F7DF8;
          background-color: rgba(0, 0, 0, 0.3);
          font-size: 16px;
          color: #fff;
          .item{
            width: 100%;
            position: absolute;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.3);
            text-align: center;
          }
        }
      }
    }
  }
}
.table-expand{
  font-size: 0;
  padding-left: 48px !important;
  label {
    width: 90px;
    color: #99a9bf;
  }
  .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 25%;
  }
}
.no-down {
  ::v-deep .el-input__suffix {
    display: none;
  }

  ::v-deep .el-select-dropdown {
    display: none;
  }
}
</style>

<style lang="scss">
.full-width{
  .el-form-item__label{
    width: 100%;
  }
}
.list-wrap{
  .el-form-item__content{
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    margin-top: 20px;
    >div:first-child{
      display: flex;
      align-items: flex-start;
      flex-wrap: wrap;
    }
  }
}
</style>
